<template>
  <view class="category-container">
    <!-- 状态栏占位 -->
    <view class="status-bar"></view>
    
    <!-- 头部 -->
    <view class="header">
	     <NavBarVue>这里是头部</NavBarVue>
      <view class="header-content">
		   
			<!-- 在header-content内添加 -->
			
        <text class="page-title">{{ categoryName || '行业板块' }}</text>
        <view class="filter-btn" @tap="showFilterOptions">
          <image class="filter-icon" src="/static/icons/filter.png"></image>
          <text>点击{{na}}筛选</text>
        </view>
      </view>
      
      <!-- 分类标签 -->
     <!-- <scroll-view class="tag-scroll" scroll-x>
        <view class="tag-container">
          <view 
            class="category-tag" 
            :class="{ active: activeCategoryId === category.id }" 
            v-for="(category, index) in categoryList" 
            :key="index"
            @tap="changeCategory(category.id)"
          >
            {{ category.name }}
          </view>
        </view>
      </scroll-view> -->
    </view>
    
    <!-- 筛选选项 -->
    <view class="filter-options" v-if="showFilter">
		<view class="filter-section">
		  <text class="filter-title">二级分类</text>
		  <view class="filter-tags">
		    <view 
		      class="filter-tag" 
		      :class="{ active: filters.cate02 === type.code02 }" 
		      v-for="(type, index) in unprojectTwo" 
		      :key="index"
		      @tap="setFilter('cate02', type.code02)"
		    >
		      {{ type.code02}}
		    </view>
		  </view>
		</view>
		
		 <view class="filter-section hidden">
		  <text class="filter-title">三级分类</text>
		  <view class="filter-tags">
		     <view 
		      class="filter-tag" 
		      :class="{ active: filters.cate03 === type.code03.codeid }" 
		      v-for="(type, index) in projectThree" 
		      :key="index"
		      @tap="setFilter('cate03', type.code03.codeid)"
		    >
		      {{ type.code03.code03}}
		    </view> 
		  </view>
		</view> 
		
     <!-- <view class="filter-section">
        <text class="filter-title">项目类型</text>
        <view class="filter-tags">
          <view 
            class="filter-tag" 
            :class="{ active: filters.type === type.value }" 
            v-for="(type, index) in projectTypes" 
            :key="index"
            @tap="setFilter('type', type.value)"
          >
            {{ type.label }}
          </view>
        </view>
      </view> -->
      
     <!-- <view class="filter-section">
        <text class="filter-title">预算范围</text>
        <view class="filter-tags">
          <view 
            class="filter-tag" 
            :class="{ active: filters.budget === budget.value }" 
            v-for="(budget, index) in budgetRanges" 
            :key="index"
            @tap="setFilter('budget', budget.value)"
          >
            {{ budget.label }}
          </view>
        </view>
      </view> -->
      
      <!-- <view class="filter-section">
        <text class="filter-title">项目区域</text>
        <view class="filter-tags">
          <view 
            class="filter-tag" 
            :class="{ active: filters.region === region.value }" 
            v-for="(region, index) in regions" 
            :key="index"
            @tap="setFilter('region', region.value)"
          >
            {{ region.label }}
          </view>
        </view>
      </view> -->
	  
      
      <view class="filter-actions">
        <button class="reset-btn" @tap="resetFilters">重置</button>
        <button class="apply-btn" @tap="applyFilters">确定</button>
      </view>
    </view>
    
    <!-- 项目列表 -->
    <scroll-view class="project-scroll" scroll-y @scrolltolower="loadMore" :style="{ height: contentHeight + 'px' }">
      <view class="project-list">
        <view class="project-card" v-for="(project, index) in projectList" :key="index" @tap="goToProjectDetail(project)">
          <view class="project-header">
            <text class="project-title">{{ project.title }}</text>
            <view class="tag project-type" :class="project.isUrgent ? 'urgent' : ''">{{ project.project_type }}</view>
          </view>
          
          <view class="project-info-line">
            <view class="company-info" v-if="project.is_qi == '是' ">
              <image class="company-logo" src="/static/images/qi.png" mode="aspectFill"></image>
              <text class="company-name">{{project.company_name}}</text>
            </view>
            <text class="publish-date">{{ project.created_at }}</text>
          </view>
          
          <view class="project-details">
            <view class="detail-item">
              <text class="detail-label">预算：</text>
              <text class="detail-value price">￥{{ project.budget_min }}{{ project.budgetUnit }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">地区：</text>
              <text class="detail-value">{{ project.location }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">截止：</text>
              <text class="detail-value">{{ project.deadline }}</text>
            </view>
          </view>
          
          <!-- <view class="project-tags">
            <view class="tag" v-for="(tag, tagIndex) in project.tags" :key="tagIndex">{{ tag }}</view>
          </view> -->
          
          <view class="project-actions">
            <!-- <button class="action-btn primary" @tap.stop="goToBid(project)">投标</button>
            <button class="action-btn secondary" @tap.stop="toggleFavorite(project)">
              <image class="action-icon" :src="project.isFavorite ? '/static/icons/star-fill.png' : '/static/icons/star.png'"></image>
              <text>{{ project.isFavorite ? '已收藏' : '收藏' }}</text>
            </button> -->
          </view>
        </view>
        
        <!-- 加载状态 -->
        <view class="loading-container" v-if="loading">
          <view class="loading-spinner"></view>
          <text>加载中...</text>
        </view>
        
        <view class="no-more" v-if="!hasMore && projectList.length > 0">
          <text>没有更多项目了</text>
        </view>
        
        <view class="empty-state" v-if="!loading && projectList.length === 0">
          <image class="empty-icon" src="/static/icons/empty.png"></image>
          <text class="empty-text">暂无符合条件的项目</text>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted ,computed} from 'vue'
import NavBarVue from '../../components/common/NavBar.vue'
import { onLoad} from '@dcloudio/uni-app'
// 路由参数
const props = defineProps({
  id: String,
  name: String
})

// 响应式数据
const categoryId = ref(props.id || '')
const categoryName = ref(props.name || '行业板块')
const activeCategoryId = ref(categoryId.value ? parseInt(categoryId.value) : 0)
const showFilter = ref(true)
const contentHeight = ref(0)
const loading = ref(false)
const hasMore = ref(true)
const page = ref(1)
const pageSize = ref(10)

// 分类列表
const categoryList = ref([
  { id: 0, name: '全部' },
  { id: 1, name: '机械设备' },
  { id: 2, name: '电子电气' },
  { id: 3, name: '建筑工程' },
  { id: 4, name: '信息技术' },
  { id: 5, name: '医疗器械' },
  { id: 6, name: '环保节能' },
  { id: 7, name: '服装纺织' },
  { id: 8, name: '食品饮料' },
  { id: 9, name: '化工材料' },
  { id: 10, name: '其他' }
])

// 二级筛选选项
const projectTwo = ref([])
const unprojectTwo = computed(() => {
  const seen = new Set(); // 用于存储已经出现过的 code02 值
  return projectTwo.value
    .filter(item => item.code02 !== null && item.code02 !== "") // 过滤掉空值
    .filter(item => {
      if (!seen.has(item.code02)) {
        seen.add(item.code02); // 添加到 Set 中
        return true; // 保留该项
      }
      return false; // 去重
    });
});
// 三级筛选选项
// 动态加载三级分类
const projectThree = computed(() => {
  if (!filters.value.cate02) {
    return [];
  }
  return projectTwo.value
    .filter(item => item.code02 === filters.value.cate02 && item.code03 !== null && item.code03 !== "")
    .map(item => ({ code03: item }));
});

// 设置过滤条件
const setFilter = (key, value) => {
  filters.value[key] = value;
  if (key === 'cate02') {
    filters.value.cate03 = null; // 重置三级分类
  }
};

// 筛选选项
const projectTypes = ref([
  { label: '全部', value: '' },
  { label: '公开招标', value: 'public' },
  { label: '邀请招标', value: 'invite' },
  { label: '竞争性谈判', value: 'negotiation' },
  { label: '询价采购', value: 'inquiry' }
])

const budgetRanges = ref([
  { label: '全部', value: '' },
  { label: '10万以下', value: 'under_100k' },
  { label: '10-50万', value: '100k_500k' },
  { label: '50-100万', value: '500k_1m' },
  { label: '100-500万', value: '1m_5m' },
  { label: '500万以上', value: 'above_5m' }
])

const regions = ref([
  { label: '全部', value: '' },
  { label: '北京', value: 'beijing' },
  { label: '上海', value: 'shanghai' },
  { label: '广州', value: 'guangzhou' },
  { label: '深圳', value: 'shenzhen' },
  { label: '杭州', value: 'hangzhou' },
  { label: '南京', value: 'nanjing' },
  { label: '成都', value: 'chengdu' },
  { label: '武汉', value: 'wuhan' },
  { label: '西安', value: 'xian' },
  { label: '重庆', value: 'chongqing' }
])

const filters = ref({
	cate02:'',//二级分类
	cate03:'',//三级分类
  // type: '',//类型
  // budget: '',//预算
  // region: ''//区域
})

// 项目列表
const projectList = ref([])
const na = ref("")
onLoad((options)=>{
	na.value = decodeURIComponent(options.name)
	console.log("获得大类名",na)
	//发送请求
	uni.request({
		url:'http://115.190.38.218/go/api/v1/categories',
		method:'GET',
		data:{
			name:na.value,
			
		},
		success:function(res){
			console.log("获取结果：",res)
			projectTwo.value = res.data.data
		},
		fail:function(err){
			console.log("出现错误：",err)
		}
	})
})

// 初始化
onMounted(() => {
	console.log("进入这里吗")
  // 设置页面内容高度
  const systemInfo = uni.getSystemInfoSync()
  const statusBarHeight = systemInfo.statusBarHeight
  contentHeight.value = systemInfo.windowHeight - statusBarHeight - 190 // 头部高度约为190px
  
  // 加载项目列表
  //fetchProjects()
})

// 方法
const showFilterOptions = () => {
  showFilter.value = !showFilter.value
}

const changeCategory = (categoryId) => {
  activeCategoryId.value = categoryId
  page.value = 1
  projectList.value = []
  hasMore.value = true
  fetchProjects()
}

// const setFilter = (key, value) => {
//   filters.value[key] = value
// }

const resetFilters = () => {
  filters.value = {
    type: '',
    budget: '',
    region: ''
  }
}

const applyFilters = () => {
	console.log("打印已选的种类：",filters.value)
	getProject(filters.value.cate03)
	
   showFilter.value = false
  // page.value = 1
  // projectList.value = []
  // hasMore.value = true
  //fetchProjects()
}
const getProject = (r1)=>{
	console.log("传入的值：",r1)
	uni.request({
		url:'http://115.190.38.218/go/api/v1/projts',
		method:'GET',
		data:{
			le01:r1,
			
		},
		success:function(res){
			console.log("获取的值：",res)
			projectList.value = res.data.data.projects
		},
		fail:function(err){
			console.log("出错：",err)
		}
	})
}
const loadMore = () => {
  if (!loading.value && hasMore.value) {
    page.value++
    fetchProjects()
  }
}

const fetchProjects = () => {
  if (loading.value) return
  
  loading.value = true
  //换真实请求
    uni.request({
		url:'http://115.190.38.218/go/api/v1/categories',
		method:'POST',
		success:function(res){
			console.log(res)
			
		},
		fail:function(err){
			console.log("err")
		}
	})
  //------------》
  // 模拟请求
  // setTimeout(() => {
  //   // 模拟数据
  //   const mockProjects = [
  //     {
  //       id: 101,
  //       title: '智能制造设备采购项目',
  //       company: '辽宁智造科技有限公司',
  //       companyLogo: '/static/images/company-logo1.png',
  //       type: '公开招标',
  //       isUrgent: true,
  //       budget: '680',
  //       budgetUnit: '万',
  //       region: '沈阳市',
  //       publishDate: '2天前',
  //       deadline: '2023-06-18',
  //       tags: ['智能制造', '设备采购'],
  //       isFavorite: false
  //     },

  //   ]
    
  //   // 判断是否还有更多数据
  //   const hasMoreData = page.value < 3 // 模拟只有3页数据
    
  //   // 追加新数据
  //   projectList.value = [...projectList.value, ...mockProjects]
  //   hasMore.value = hasMoreData
  //   loading.value = false
  // }, 1000)
}

const goToProjectDetail = (project) => {
	//先判断是不是企业单
	console.log("获取项目详情，看是否是企业单：",project.is_qi)
	
	//再判断当前登录的用户角色
	let user = uni.getStorageSync("info")
	if('company_name' in user){
		console.log("是企业用户")
		uni.navigateTo({
		  url: `/pages/project/project-detail?id=${project.id}`
		})
	}else{
		console.log("个人会员")
		if(project.is_qi == '是'){
			uni.showToast({
				title: '仅企业会员可接',
				icon:'fail',
				duration: 2000
			})
		}else{
				uni.navigateTo({
				  url: `/pages/project/project-detail?id=${project.id}`
				})
			}
	}
 
}

const goToBid = (project) => {
  uni.navigateTo({
    url: `/pages/bid/bid-form?projectId=${project.id}`
  })
}

const toggleFavorite = (project) => {
  project.isFavorite = !project.isFavorite
  uni.showToast({
    title: project.isFavorite ? '已收藏' : '已取消收藏',
    icon: 'success'
  })
}
</script>

<style>
	
  /* 样式部分保持不变 */
  .category-container {
    min-height: 100vh;
    background-color: #f5f7fa;
  }
  
  .status-bar {
    height: var(--status-bar-height);
    width: 100%;
    background-color: #1d4ed8;
	border: 1px solid red;
  }
  
  .header {
    background-color: #1d4ed8;
    padding-bottom: 20rpx;
	border: 1px solid green;
  }
  
  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20rpx 30rpx;
  }
  
  .page-title {
    font-size: 36rpx;
    font-weight: 600;
    color: #fff;
  }
  
  .filter-btn {
    display: flex;
    align-items: center;
    font-size: 28rpx;
    color: #fff;
  }
  
  .filter-icon {
    width: 40rpx;
    height: 40rpx;
    margin-right: 10rpx;
  }
  
  .tag-scroll {
    width: 100%;
  }
  
  .tag-container {
    display: flex;
    padding: 20rpx 30rpx;
    white-space: nowrap;
  }
  .tag-container::after {
     content: "";
      display: table;
      clear: both;
  }
  .category-tag {
    padding: 12rpx 30rpx;
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
    background-color: rgba(255, 255, 255, 0.1);
    border-radius: 30rpx;
    margin-right: 20rpx;
    display: inline-block;
	vertical-align: middle; /* 或top/bottom */
  }
  @media screen and (max-width: 768px) {
    .header-content { flex-direction: column; }
    .filter-btn { margin-top: 10px; }
  }
  .category-tag.active {
    color: #1d4ed8;
    background-color: #fff;
    font-weight: 600;
  }
  .filter-options {
    position: fixed; /* 改为fixed定位 */
    top: 180rpx; /* 根据实际header高度调整 */
    z-index: 1000;
  }
  .filter-options {
    position: absolute;
    top: var(--status-bar-height);
    margin-top: 150rpx;
    left: 0;
    right: 0;
    background-color: #fff;
    padding: 30rpx;
    z-index: 100;
    border-bottom: 1px solid #eee;
  }
  
  .filter-section {
    margin-bottom: 30rpx;
  }
  
  .filter-title {
    font-size: 30rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 20rpx;
  }
  
  .filter-tags {
    display: flex;
    flex-wrap: wrap;
  }
  
  .filter-tag {
    padding: 12rpx 30rpx;
    font-size: 26rpx;
    color: #666;
    background-color: #f3f4f6;
    border-radius: 30rpx;
    margin-right: 20rpx;
    margin-bottom: 20rpx;
  }
  
  .filter-tag.active {
    color: #fff;
    background-color: #1d4ed8;
  }
  
  .filter-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 20rpx;
  }
  
  .reset-btn, .apply-btn {
    padding: 0 40rpx;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    margin-left: 20rpx;
  }
  
  .reset-btn {
    background-color: #f3f4f6;
    color: #666;
  }
  
  .apply-btn {
    background-color: #1d4ed8;
    color: #fff;
  }
  
  .project-scroll {
    width: 100%;
  }
  
  .project-list {
    padding: 30rpx;
  }
  
  .project-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 30rpx;
    margin-bottom: 30rpx;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  }
  
  .project-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 20rpx;
  }
  
  .project-title {
    flex: 1;
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    line-height: 1.4;
  }
  
  .project-type {
    font-size: 22rpx;
    padding: 4rpx 16rpx;
    border-radius: 6rpx;
    background-color: rgba(59, 130, 246, 0.1);
    color: #3b82f6;
    white-space: nowrap;
    margin-left: 12rpx;
  }
  
  .project-type.urgent {
    background-color: rgba(239, 68, 68, 0.1);
    color: #ef4444;
  }
  
  .project-info-line {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
  }
  
  .company-info {
    display: flex;
    align-items: center;
  }
  
  .company-logo {
    width: 40rpx;
    height: 40rpx;
    border-radius: 50%;
    margin-right: 12rpx;
  }
  
  .company-name {
    font-size: 26rpx;
    color: #666;
  }
  
  .publish-date {
    font-size: 24rpx;
    color: #999;
  }
  
  .project-details {
    background-color: #f9fafb;
    border-radius: 12rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
  }
  
  .detail-item {
    display: flex;
    margin-bottom: 10rpx;
  }
  
  .detail-item:last-child {
    margin-bottom: 0;
  }
  
  .detail-label {
    font-size: 26rpx;
    color: #666;
    width: 100rpx;
  }
  
  .detail-value {
    font-size: 26rpx;
    color: #333;
    flex: 1;
  }
  
  .detail-value.price {
    color: #f97316;
    font-weight: 600;
  }
  
  .project-tags {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 20rpx;
  }
  
  .tag {
    font-size: 22rpx;
    padding: 4rpx 16rpx;
    background-color: #f3f4f6;
    color: #666;
    border-radius: 6rpx;
    margin-right: 12rpx;
    margin-bottom: 10rpx;
  }
  
  .project-actions {
    display: flex;
    justify-content: space-between;
  }
  
  .action-btn {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    border-radius: 40rpx;
    font-size: 28rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .action-btn.primary {
    background-color: #1d4ed8;
    color: #fff;
    margin-right: 20rpx;
  }
  
  .action-btn.secondary {
    background-color: #f3f4f6;
    color: #666;
  }
  
  .action-icon {
    width: 32rpx;
    height: 32rpx;
    margin-right: 10rpx;
  }
  
  .loading-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 30rpx 0;
  }
  
  .loading-spinner {
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid #f3f4f6;
    border-top: 4rpx solid #1d4ed8;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 10rpx;
  }
  
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }
  
  .no-more, .empty-state {
    text-align: center;
    padding: 30rpx 0;
    color: #999;
    font-size: 26rpx;
  }
  
  .empty-state {
    padding: 100rpx 0;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  
  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
</style>